#!/usr/bin/env python3

import logging, os.path, paramiko, time, threading

# 1.创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)  # Log等级总开关,默认level是WARNING,低于该级别的就不输出了,级别排序: CRITICAL > ERROR > WARNING > INFO > DEBUG

# 2.创建一个handler，用于写入日志文件
"""
time.time():从1970年1月1日0分0时0秒起至当前时间，经过的浮点数
time.localtime()：转换为time.struct_time类型的对象的秒数
time.strftime() 函数根据指定的格式把一个时间字符串解析为时间元组
"""
log_time = time.strftime('%Y_%m_%d-%H_%M_%S', time.localtime(time.time()))
log_path = os.path.dirname(os.getcwd())   # os.getcwd() 用于返回当前工作目录
log_name = log_path + log_time + '.log'
log_file = log_name
fh = logging.FileHandler(log_file, mode='w')
fh.setLevel(logging.INFO)  # 输出到file的log等级的开关
# output to console
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)

# 3.定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)

# 4.将logger添加到handler里面
logger.addHandler(fh)
# output to console
ch.setFormatter(formatter)
logger.addHandler(ch)

def thread_ssh2_log(ip, port, username, password, cmd_list, verbose=True):
    try:
        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, port, username, password, timeout=3, compress=True)
        chan = ssh.invoke_shell()
        time.sleep(1)
        x = chan.recv(2048).decode()
        logging.warning('%s connect success ' % ip)

        # cisco and h3c diff
        chan.send(b'enable\n')
        # chan.send(b'su\n')
        chan.send(b'cisco\n')

        cmd_list = open('thread_ipcfg.txt', 'r')
        for cmd in cmd_list:
            chan.send(cmd.encode('utf-8'))   # 有的场景需要用到txt自带的\n
            time.sleep(1)
            x = chan.recv(40960).decode('utf-8')
            if verbose:
                print(x)
                # logging.warning('execute: \n%s' % x)

        chan.close()
        ssh.close()
        logging.warning(f'The job of {ip} is over, start next...')

    except Exception as e:
        print(f'{ip} connect failed ', e)
        logging.warning('%s connect failed ' % ip)

if __name__ == '__main__':
    import all_authen
    username = all_authen.login_user
    password = all_authen.login_token

    with open('thread_ips.txt', 'r') as ipList:
        for ip in ipList:
            threading.Thread(target=thread_ssh2_log, args=(ip.strip(), 22, username, password, [])).start()
